package com.google.code.sms.controller;

import com.google.code.sms.domain.MediaElement;
import com.google.code.sms.domain.Player;
import com.google.code.sms.domain.TransferStatus;
import com.google.code.sms.filter.ParameterDecodingFilter;
import com.google.code.sms.service.MediaElementService;
import com.google.code.sms.service.PlayerService;
import com.google.code.sms.service.StatusService;
import com.google.code.sms.util.StringUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Controller for showing what's currently playing.
 *
 * @author Sindre Mehus
 */
public class NowPlayingController extends AbstractController {

    private PlayerService playerService;
    private StatusService statusService;
    private MediaElementService mediaElementService;

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Player player = playerService.getPlayer(request, response);
        List<TransferStatus> statuses = statusService.getStreamStatusesForPlayer(player);

        MediaElement current = statuses.isEmpty() ? null : mediaElementService.getMediaElement(statuses.get(0).getFile());
        MediaElement dir = current == null ? null : mediaElementService.getParentOf(current);

        String url;
        if (dir != null) {
            url = "main.view?path" + ParameterDecodingFilter.PARAM_SUFFIX + "="
                    + StringUtil.utf8HexEncode(dir.getPath()) + "&updateNowPlaying=true";
        } else {
            url = "home.view";
        }

        return new ModelAndView(new RedirectView(url));
    }

    public void setPlayerService(PlayerService playerService) {
        this.playerService = playerService;
    }

    public void setStatusService(StatusService statusService) {
        this.statusService = statusService;
    }

    public void setMediaElementService(MediaElementService mediaElementService) {
        this.mediaElementService = mediaElementService;
    }
}
